// weather.js  - 完整实现版 (适配新API，保留定位功能)
class WeatherWidget {
    constructor() {
        // API基础配置 
        this.API_URL_BASE = 'https://cn.apihz.cn/api/tianqi/tqyb.php?id=id&key=key'; 
        this.cacheKey = 'weather_data_cache';
        this.cacheTimeout = 5 * 60 * 1000; // 5分钟缓存时间
        this.animationFrameId = null;
        this.rainDrops = [];
        this.snowFlakes = [];
        
        // 完整初始化流程 
        this.init(); 
    }
    
    // 获取天气强度因子
    getWeatherIntensity(weatherType) {
        // 小雨,中雨,大雨,暴雨,阵雨,雷阵雨,小雪,中雪,大雪,暴雪,阵雪,雨夹雪,雷阵雪
        if (weatherType.includes('暴雨') || weatherType.includes('暴雪')) {
            return 1.5; // 最强
        } else if (weatherType.includes('大雨') || weatherType.includes('大雪')) {
            return 1.0; // 强
        } else if (weatherType.includes('中雨') || weatherType.includes('中雪')) {
            return 0.6; // 中等
        } else if (weatherType.includes('阵雨') || weatherType.includes('阵雪') || 
                   weatherType.includes('雷阵雨') || weatherType.includes('雷阵雪') || 
                   weatherType.includes('雨夹雪')) {
            return 0.4; // 阵性
        } else if (weatherType.includes('小雨') || weatherType.includes('小雪')) {
            return 0.1; // 弱
        }
        return 0.1; // 默认强度
    }
    
    // 缓存天气数据 - 使用session缓存
    cacheWeatherData(data) {
        try {
            const cacheItem = {
                data: data,
                timestamp: Date.now()
            };
            sessionStorage.setItem(this.cacheKey, JSON.stringify(cacheItem));
        } catch (error) {
            console.error(' 缓存天气数据失败:', error);
        }
    }
    
    // 获取缓存的天气数据 - 使用session缓存
    getCachedWeatherData() {
        try {
            const cached = sessionStorage.getItem(this.cacheKey);
            if (!cached) return null;
            
            const cacheItem = JSON.parse(cached);
            const now = Date.now();
            
            // 检查缓存是否过期
            if (now - cacheItem.timestamp < this.cacheTimeout) {
                return cacheItem.data;
            } else {
                // 缓存过期，删除
                sessionStorage.removeItem(this.cacheKey);
                return null;
            }
        } catch (error) {
            console.error(' 获取缓存天气数据失败:', error);
            sessionStorage.removeItem(this.cacheKey);
            return null;
        }
    }

 

    init() {
        this.cacheElements(); 
        this.initCanvas(); 
        this.getCityAndFetchWeather(); 
    } 

    cacheElements() {
        this.elements = {
            loader: document.querySelector('.loader'), 
            content: document.querySelector('.content'), 
            errorOverlay: document.querySelector('.error-overlay'), 
            place: document.getElementById('place'), 
            temperature: document.getElementById('temperature'), 
            windSpeed: document.getElementById('windSpeed'), 
            humidity: document.getElementById('humidity'), 
            updateTime: document.getElementById('updateTime'), 
            weatherIcon: document.getElementById('weatherIcon'), 
            canvas: document.getElementById('weatherCanvas'),
            cacheStatus: document.getElementById('cacheStatus'),
            lastUpdated: document.querySelector('.last-updated')
        };
    } 

    initCanvas() {
        this.ctx  = this.elements.canvas.getContext('2d'); 
        this.elements.canvas.width  = 120; 
        this.elements.canvas.height  = 120; 
    } 

    async getCityAndFetchWeather() {
        try {
            // 检查是否有缓存的天气数据
            const cachedData = this.getCachedWeatherData();
            if (cachedData) {
                console.log(' 使用缓存的天气数据');
                this.elements.cacheStatus.textContent = '使用缓存数据';
                this.updateDisplay(cachedData, true); // 第二个参数表示使用缓存数据
                this.showContent();
            } else {
                // 没有缓存或缓存过期，获取定位
                this.elements.cacheStatus.textContent = '';
                const location = await parseTencentLocation();
                // console.log(' 完整定位数据:', location);
                if (!location.province)  {
                    throw new Error('无法获取省份信息');
                }

                // 地址备用方案 
                const fallbackPlace = location.district  || location.city  || location.province;
                if (!fallbackPlace) {
                    throw new Error('无法获取有效地点信息');
                }

                await this.fetchWeather({
                    province: location.province,
                    place: fallbackPlace,
                });
            }
        } catch (error) {
            console.error(' 定位流程失败:', error);
            this.elements.cacheStatus.textContent = '';
            this.showError();
        }
    }
 

    async fetchWeather(locationInfo) {
        try {
            // 参数处理 
            const processName = (name) => {
                if (!name) return '';
                return name.replace(/[ 省市县区]$/, '').trim();
            };

            const params = new URLSearchParams({
                sheng: processName(locationInfo.province), 
                place: processName(locationInfo.place) 
            });

            // 调试输出 
            console.log(' 最终请求参数:', params.toString()); 

            // 发起请求 
            const response = await fetch(`${this.API_URL_BASE}&${params}`);
            if (!response.ok)  {
                throw new Error(`HTTP错误 ${response.status}`); 
            }

            const data = await response.json(); 
            console.log(' 原始API响应:', data);

            if (data.code  !== 200) {
                throw new Error(data.msg  || 'API返回异常状态码');
            }

            this.updateDisplay(data, false); // 第二个参数表示不使用缓存数据
            this.showContent(); 
        } catch (error) {
            console.error(' 获取天气失败:', error);
            this.showError(); 
        }
    } 

    updateDisplay(data, useCachedData = false) {
        // 缓存天气数据
        this.cacheWeatherData(data);
        
        // 完整数据映射 
        // 添加国家显示
        const country = '中国'; // 默认显示中国
        
        const displayData = {
            place: `${country} ${data.sheng} ${data.shi}` || '未知地区',
            temperature: data.nowinfo.temperature ? `${data.nowinfo.temperature}°` : '--',
            windSpeed: data.nowinfo.windScale ? `${data.nowinfo.windScale}` : '--',
            humidity: data.nowinfo.humidity ? `${data.nowinfo.humidity}%` : '--',
            // 始终使用当前时间作为更新时间，避免API返回固定值的问题
            updateTime: new Date().toLocaleString(),
            weatherIcon: data.weather1img || ''
        };

        // 更新DOM元素 
        this.elements.place.textContent = displayData.place;
        this.elements.temperature.textContent = displayData.temperature; 
        this.elements.windSpeed.textContent = displayData.windSpeed; 
        this.elements.humidity.textContent = displayData.humidity; 
        
        // 使用缓存数据时不显示上次更新时间，显示缓存状态
        if (useCachedData) {
            this.elements.updateTime.textContent = '';
            this.elements.lastUpdated.style.display = 'none';
            this.elements.cacheStatus.style.display = 'block';
        } else {
            this.elements.updateTime.textContent = ` ${displayData.updateTime}`;
            this.elements.lastUpdated.style.display = 'block';
            this.elements.cacheStatus.style.display = 'none';
        }
        
        // 更新welcomeMsg div的内容
        const welcomeMsgElement = document.getElementById('welcomeMsg');
        if (welcomeMsgElement) {
            welcomeMsgElement.textContent = `欢迎来自${displayData.place}的朋友访问`;
        }

        // 图标处理 - 使用API提供的图片
        if (displayData.weatherIcon) {
            this.elements.weatherIcon.style.backgroundImage = `url(${displayData.weatherIcon})`;
            this.elements.weatherIcon.alt = data.weather1 || '天气图标';
        } else {
            // 添加默认测试图片作为fallback
            this.elements.weatherIcon.style.backgroundImage = `url('URL')`;
            this.elements.weatherIcon.alt = '默认天气图标';
        }
        // 更新天气动画
        this.updateWeatherAnimation(data.weather1 || '');
    }
 

    updateWeatherAnimation(weatherType) {
        // 取消之前的动画
        if (this.animationFrameId) {
            cancelAnimationFrame(this.animationFrameId);
            this.animationFrameId = null;
        }
        
        // 清空粒子数组
        this.rainDrops = [];
        this.snowFlakes = [];
        // 清空画布
        this.ctx.clearRect(0, 0, 120, 120);
        
        // 只绘制雨滴和雪花动画，其他天气类型不绘制
        if (weatherType.includes('雨')) {
            // 根据雨的强度设置下落速度
            const speedFactor = this.getWeatherIntensity(weatherType);
            this.animateRain(speedFactor);
        } else if (weatherType.includes('雪')) {
            // 根据雪的强度设置下落速度
            const speedFactor = this.getWeatherIntensity(weatherType);
            this.animateSnow(speedFactor);
        }
        // 其他天气类型不执行任何绘制，保留API返回的图片显示
    }
 

    showContent() {
        this.elements.loader.style.display  = 'none';
        this.elements.content.style.opacity  = '1';
        this.elements.errorOverlay.style.display  = 'none';
    } 

    showError() {
        this.elements.loader.style.display  = 'none';
        this.elements.errorOverlay.style.display  = 'flex';
    } 


    animateRain(speedFactor = 1) {
        // 初始化雨滴
        if (this.rainDrops.length === 0) {
            for (let i = 0; i < 20; i++) {
                this.rainDrops.push({
                    x: Math.random() * 120,
                    y: Math.random() * 120,
                    speed: 2 + Math.random() * 3 * speedFactor,
                    length: 6 + Math.random() * 6,
                    thickness: 1 + Math.random() * 1.5
                });
            }
        }
        const render = () => {
            this.ctx.clearRect(0, 0, 120, 120);
            this.ctx.strokeStyle = 'rgba(0, 120, 255, 0.6)';
            for (let i = 0; i < this.rainDrops.length; i++) {
                const drop = this.rainDrops[i];
                this.ctx.lineWidth = drop.thickness;
                this.ctx.beginPath();
                this.ctx.moveTo(drop.x, drop.y);
                this.ctx.lineTo(drop.x + 3, drop.y + drop.length);
                this.ctx.stroke();
                
                // 更新位置
                drop.y += drop.speed;
                drop.x += 0.5;
                
                // 如果雨滴移出画布，重新放置在顶部
                if (drop.y > 120) {
                    drop.y = -drop.length;
                    drop.x = Math.random() * 120;
                }
            }
                        this.animationFrameId = requestAnimationFrame(render);
        };
        render();
    }
 

    animateSnow(speedFactor = 1) {
        // 初始化雪花
        if (this.snowFlakes.length === 0) {
            for (let i = 0; i < 30; i++) {
                this.snowFlakes.push({
                    x: Math.random() * 120,
                    y: Math.random() * 120,
                    speed: 1 + Math.random() * 1.5 * speedFactor,
                    radius: 1 + Math.random() * 2,
                    sway: Math.random() * 0.5
                });
            }
        }
        
        const render = () => {
            this.ctx.clearRect(0, 0, 120, 120);
            
            // 根据系统深色模式设置雪花颜色
            const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
            this.ctx.fillStyle = isDarkMode ? 'rgba(220, 220, 220, 0.8)' : 'rgba(255, 255, 255, 0.8)';
            
            for (let i = 0; i < this.snowFlakes.length; i++) {
                const flake = this.snowFlakes[i];
                this.ctx.beginPath();
                this.ctx.arc(flake.x, flake.y, flake.radius, 0, Math.PI * 2);
                this.ctx.fill();
                
                // 更新位置
                flake.y += flake.speed;
                flake.x += Math.sin(Date.now() * 0.001 + i) * flake.sway;
                
                // 如果雪花移出画布，重新放置在顶部
                if (flake.y > 120) {
                    flake.y = -flake.radius;
                    flake.x = Math.random() * 120;
                }
            }
            
            this.animationFrameId = requestAnimationFrame(render);
        };
        
        render();
    }
}
// 腾讯地图定位服务（完整实现）
const TENCENT_MAP_API_KEY = "KEY";
const parseTencentLocation = () => {
    return new Promise((resolve, reject) => {
        const callbackName = 'tencentLocationCallback';
        const timeout = setTimeout(() => {
            reject(new Error('定位请求超时'));
            cleanup();
        }, 8000);

        const cleanup = () => {
            clearTimeout(timeout);
            delete window[callbackName];
            script.remove(); 
        };

        window[callbackName] = (response) => {
            if (response.status  === 0) {
                const info = response.result.ad_info; 
                resolve({
                    province: info.province, 
                    city: info.city, 
                    district: info.district, 
                    full: info 
                });
            } else {
                reject(new Error(`定位失败: ${response.message}`)); 
            }
            cleanup();
        };

        const script = document.createElement('script'); 
        script.src  = `https://apis.map.qq.com/ws/location/v1/ip?key=${TENCENT_MAP_API_KEY}&output=jsonp&callback=${callbackName}`; 
        script.onerror  = () => {
            reject(new Error('无法加载定位脚本'));
            cleanup();
        };
        document.body.appendChild(script); 
    });
};
// 初始化入口 
document.addEventListener('DOMContentLoaded',  () => {
    try {
        new WeatherWidget();
    } catch (error) {
        console.error(' 初始化失败:', error);
        document.querySelector('.error-overlay').style.display  = 'flex';
    }
});